<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\ActionLog;
use think\Request;
use think\Response;

/**
 * 行为日志-服务类
 *
 * @author  牧羊人
 * @since   2020/11/20
 * Class ActionLogService
 * @package app\admin\service
 */
class ActionLogService extends BaseService
{
    /**
     * 构造函数
     *
     * @author 牧羊人
     * @since  2020/11/20
     * ActionLogService constructor.
     */
    public function __construct()
    {
        $this->model = new ActionLog();
    }

    /**
     * 获取数据列表
     *
     * @author 牧羊人
     * @return array
     * @since  2020/11/20
     */
    public function getList()
    {
        $param = request()->param();
        $map   = [['type', '=', 1]];
        if (!empty($param['date'])) {
            $map[] = ['create_time', 'between', [strtotime($param['date'][0]), strtotime($param['date'][1]) + 86399]];
        }
        $data = $this->model->where($map)
            ->order('id', 'desc')
            ->paginate(PERPAGE)
            ->each(
                function ($val) {
                    $this->formatLog($val);
                    $val->response = json_decode($val->response, true);
                }
            );

        return [
            'msg'   => 'success',
            'code'  => 0,
            'data'  => $data->items(),
            'count' => $data->total(),
        ];
    }

    public function export()
    {
        set_time_limit(0);
        $fileName = '系统操作日志';
        $param    = request()->param();
        $map      = [['type', '=', 1]];
        if (!empty($param['date'])) {
            $begin = strtotime($param['date'][0]);
            $end   = strtotime($param['date'][1]) + 86399;
            $map[] = ['create_time', 'between', [$begin, $end]];

            $fileName .= ' ' . date('Y-m-d', $begin);
            if ($end - $begin >= 86400) {
                $fileName .= '~' . date('Y-m-d', $end);
            }
        }

        $lastId  = $this->model->where($map)->max('id') + 1;
        $limit   = 1000;
        $csvData = [];
        do {
            $data = $this->model->where($map)
                ->where('id', '<', $lastId)
                ->limit($limit)
                ->order('id', 'desc')
                ->select();
            foreach ($data as $val) {
                $val       = $this->formatLog($val);
                $csvData[] = [
                    'app'         => $val->app,
                    'username'    => $val->username,
                    'module'      => $val->module,
                    'title'       => $val->title,
                    'param'       => json_encode($val->param, JSON_HEX_APOS | JSON_HEX_QUOT),
                    'status_code' => $val->status_code,
                    'response'    => $val->response,
                    'url'         => $val->url,
                    'ip'          => $val->ip,
                    'create_time' => date('Y-m-d H:i:s', $val->create_time)
                ];

                $lastId = $val->id;
            }
        } while (count($data) == $limit);

        $cell = [
            'app'         => '系统',
            'username'    => '账号',
            'module'      => '模块',
            'title'       => '操作',
            'status_code' => '状态码',
            'param'       => '原始请求',
            'response'    => '原始响应',
            'url'         => '请求地址',
            'ip'          => 'IP地址',
            'create_time' => '时间',
        ];
        download_csv($fileName, $cell, $csvData);
        die();
    }

    private function formatLog($log)
    {
        [$log->app, $log->module, $title, $type] = static::analysisPath($log->action);
        if (empty($log->title)) {
            $log->title = $title;
        }
        if ($log->param) {
            $param = json_decode($log->param, true);
            if (isset($param['s'])) {
                unset($param['s']);
            }
            if (isset($param['password'])) {
                $param['password'] = str_pad('', strlen($param['password']), '*');
            }
            foreach ($param as &$v) {
                $v = $this->hidePhone($v);
            }
            unset($v);
            $log->param = $param;
            if ($log->title == '编辑') {
                $log->content = $param['name'] ?? ($param['title'] ?? ($param['id'] ?? ''));
                if (empty($param['id'])) {
                    $log->title = '添加';
                }
            }
            if ($log->title == '删除') {
                $log->content = $param['id'] ?? '';
            }
            $log->username = $log->user['nickname'] ?? '';
            if (empty($val->username)) {
                $log->username = $param['username'] ?? '';
            }
            $log->username = $this->hidePhone($log->username);
        }

        return $log;
    }

    private function hidePhone($val)
    {
        if (!is_array($val) && preg_match('/^1[3-9]\d{9}$/', $val)) {
            $val = substr($val, 0, 3) . '****' . substr($val, 7);
        }

        return $val;
    }

    public static function record(Request $request, $response)
    {
        try {
            [$app, $module, $title, $type] = static::analysisPath($request->path());
            $param = $request->param();
            if (isset($param['_userId'])) {
                unset($param['_userId']);
            }
            if ($response instanceof Response) {
                $statusCode = $response->getCode();
                $response   = $type == 'query' ? '' : $response->getContent();
            } else {
                $statusCode = 500;
                $response   = $response->getMessage();
            }
            $log = [
                'username'    => '',
                'module'      => $app,
                'action'      => $request->path(),
                'method'      => $request->method(),
                'url'         => $request->url(true), // 获取完成URL
                'param'       => json_encode($param),
                'response'    => $response,
                'status_code' => $statusCode,
                'title'       => $title == $request->action() ? '' : $title,
                'type'        => $type == 'query' ? 2 : 1,
                'content'     => '',
                'ip'          => $request->ip(),
                'user_agent'  => $request->server('HTTP_USER_AGENT'),
                'create_user' => $request->_userId ?? 0,
                'create_time' => time(),
            ];
            ActionLog::insert($log);
        } catch (\Exception $exception) {
        }
    }

    private static function analysisPath($path): array
    {
        $config = config();
        $map    = [];
        foreach ($config['router_map'] ?? [] as $appKey => $val) {
            foreach ($val as $handleKey => $v) {
                foreach ($v as $pathKey => $pathName) {
                    $map[$pathKey] = ['name' => $pathName, 'app' => $appKey, 'handle' => $handleKey];
                }
            }
        }
        $defMap = ['index' => '列表', 'edit' => '编辑', 'delete' => '删除'];

        $router = trim(trim($path, '/'));
        if ($pos = strpos($router, '?')) {
            $router = substr($router, 0, $pos);
        }
        $router = explode('/', $router);

        $controller = camel_case_to_snake_case($router[0] ?? '');
        $action     = $router[1] ?? '';
        $mapAction  = $controller . '/' . $action;

        return [
            $map[$mapAction]['app'] ?? 'admin',
            ($map[$controller]['name'] ?? $controller) ?: $controller,
            ($map[$mapAction]['name'] ?? ($defMap[$action] ?? $action)) ?: $action,
            $action == 'index' ? 'query' : (in_array(
                $action,
                ['edit', 'delete']
            ) ? 'handle' : ($map[$mapAction]['handle'] ?? 'query'))
        ];
    }
}